<?php
namespace app\api\controller;
use app\common\controller\BaseApi;

/* 制卡软件接口 */
class MakeCardSoft extends  BaseApi
{
	public function _initialize()
    {
    }
	
	/**
	 * 获取店铺配置
	 * @param $access_type 访问类型  1客户端访问 
	 * @param $shop_code 店铺代码
	 * smartgym.com/api/MakeCardSoft/login/无手环健身房/password/123456
	 */
	function login(){
		$account=input('account');
		$password=md5(input('password/s'));
		$open_type=input("open_type",1);//1 软件打卡  2快捷打开  
		
		if(empty($account)||empty($password)){
			$this->api_ajax_error('','参数错误！');
		}else{			
			$admin=db("admin")->where("account='$account' and password='$password'")->fetchsql(FALSE)->find();
			if(empty($admin)){
				$this->api_ajax_error('',"账号或者密码错误！");
			}else{
				if(empty($admin['shop_id'])){//运营端账号
					$list=db("PcConfig")->alias("a")->fetchsql(FALSE)->join([['m_shop b','a.shop_id=b.id','left']])->order("b.parent_id desc")->where("b.parent_id !=0")->field("b.shop_name,a.card_keys,a.shop_id")->select();
					$data['user_type']=2;
				}else{//客户端账号
					$list=db("PcConfig")->alias('a')->fetchsql(FALSE)->join([['m_shop b','a.shop_id=b.id','left']])->order("b.parent_id desc")->where("a.shop_id=".$admin['shop_id'])->field("b.shop_name,a.card_keys,a.shop_id,a.is_locker,a.reader_version,a.locker_version,a.gym_type")->select();
					$data['user_type']=1;
				}
				foreach ($list as $key => $value){
					$list[$key]['card_keys']=$this->base64($value['card_keys']);
				}
				$data['open_type']=$open_type;
				$data['list']=$list;
				db("MakeCardSoftLog")->insert(array("admin_id"=>$admin['id'],'admin_account'=>$admin['account'],'admin_mobile'=>$admin['mobile'],'admin_name'=>$admin['name'],"open_type"=>$open_type,"shop_id"=>$admin['shop_id'],"ip"=>request()->ip()));
				$this->api_ajax_success($data,'成功');
			}
		}	
	}
	
	function base64($data){
		return base64_encode(base64_encode($data));
	}
	/**
	 *  获取制管理卡密码
	 * smartgym.com/api/MakeCardSoft/VarifyAdminCode/shop_id/4/code/1234
	 */
	function VarifyAdminCode(){
		$shop_id=input("shop_id/d");
		$code=input("code/d");
		if(empty($shop_id)||empty($code)){
			$this->api_ajax_error("","错误的shop_id,或者错误的code");
		}
		$auth_code=config("admin_auth_code")['auth_code'];
		if(!isset($auth_code[$shop_id])){//发送短信  生成验证码
			$this->api_ajax_error("","请联系运营人员获取验证码");
		}else{//
			if($code==$auth_code[$shop_id]){
				$this->api_ajax_success("","成功");
			}else{
				$this->api_ajax_error("","验证码错误");
			}
		}
	}
	/**
	 *通知管理员
	 * smartgym.com/api/MakeCardSoft/NotifyAdmin/shop_id/4
	 * */
	function NotifyAdmin(){
		$shop_id=input("shop_id/d");
		$auth_code=config("admin_auth_code")['auth_code'];
		if(!isset($auth_code[$shop_id])){//发送短信  生成验证码
		    $code=rand(1000,9999);
		    $shop_name=db("shop")->where("id=$shop_id")->value("shop_name");
			$auth_code[$shop_id]=$code;
			sp_dynamic_config("admin_auth_code",["auth_code"=>$auth_code]);
			$this->send_msg_code($shop_name,"13886369528",$code);
			
		}
		$this->api_ajax_success("","已通知到运营人员！请耐心等候");		
	}
	/**
	 * 制卡成功回调
	 * smartgym.com/api/MakeCardSoft/SuccessCallBack/shop_id/4/admin_account/安科门店1
	 * */
	function SuccessCallBack(){
		$shop_id=input("shop_id/d",0);
		$admin_account=input("admin_account");
		$admin=db("admin")->where("account='$admin_account'")->fetchsql(FALSE)->find();
		if(empty($admin)){
			$this->api_ajax_error('',"账号");
		}else{
			db("MakeCardSoftLog")->insert(array("admin_id"=>$admin['id'],'admin_account'=>$admin['account'],'admin_mobile'=>$admin['mobile'],'admin_name'=>$admin['name'],"open_type"=>1,"shop_id"=>$admin['shop_id'],"opt_type"=>2,"ip"=>request()->ip()));
			$auth_code=config("admin_auth_code")['auth_code'];
			if(isset($auth_code[$shop_id])){
				unset($auth_code[$shop_id]);
			}
			sp_dynamic_config("admin_auth_code",["auth_code"=>$auth_code]);
			$this->api_ajax_success('',"成功");
		}
	}
	/**
	 * 获取验证码
	 * smartgym.com/api/MakeCardSoft/GetCode/shop_id/4
	 * */
	function GetCode(){
		$shop_id=input("shop_id",0);
		if(empty($shop_id)){
			var_dump("参数错误");die;
		}
		$auth_code=config("admin_auth_code")['auth_code'];
		if(!isset($auth_code[$shop_id])){
			var_dump("验证码不存在");die;
		}else{
			var_dump($auth_code[$shop_id]);die;	
		}
	}
	/**
 * 发送短信验证码
 * */
function send_msg_code($shop_name,$mobile,$code){
	if(preg_match("/^1[345678]\d{9}$/", $mobile)){		
			$content="场馆名称:$shop_name".",验证码：".$code;//
			$url="http://www.ztsms.cn:8800/sendSms.do?username=xiaolijob&password=2rCXWG71&mobile=$mobile&content=场馆申请制管理卡!".$content."【场馆智能】&dstime=&productid=95533&xh=";
			$ch = curl_init($url);
			curl_setopt($ch, CURLOPT_HEADER, FALSE);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER,TRUE);
			curl_setopt($ch, CURLOPT_TIMEOUT, 5);
		    $result=curl_exec($ch); 
			if(strpos('1,', $result)==0){
				return array("flag"=>true,"data"=>$code,"msg"=>"成功");
			}else{
				return array("flag"=>false,"data"=>$result,"msg"=>"发送失败");
			}
		}else{
				return array("flag"=>false,"data"=>"","msg"=>"手机号码格式错误");
		}
}

function trimall($str)//删除空格
{
    $qian=array(" ","　","\t","\n","\r");$hou=array("","","","","");
    return str_replace($qian,$hou,$str);    
}

/*获取网络数据*/
function get_net_data($url) {
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
		return curl_exec($ch);
}
	/**
	 * smartgym.com/api/MakeCardSoft/test
	 * */
//	function test(){
//		var_dump(openssl_decrypt(base64_decode('txQuKgE7gTx/yk3pZ2IJ3w=='), "aes-256-cbc", $this->Key, true, str_repeat(chr(0), 16)));
//	}
	function encrypt($id){
	    $id=serialize($id);
	    $key="384f8f5b973f8518a1f70fd40d26b310";
	    $data['iv']=base64_encode(substr('fdakinel;injajdji',0,16));
	    $data['value']=openssl_encrypt($id, 'AES-128-CBC',$key,0,base64_decode($data['iv']));
	    $encrypt=json_encode($data);
		var_dump($id);die;
	    return $encrypt;
	}
	
	function decrypt($encrypt)
	{
	    $key = '384f8f5b973f8518a1f70fd40d26b310';//解密钥匙   
	    $encrypt = json_decode(base64_decode($encrypt), true);
	    $iv = base64_decode($encrypt['iv']);
	    $decrypt = openssl_decrypt($encrypt['value'], 'AES-128-CBC', $key, 0, $iv);
	    $id = unserialize($decrypt);
	    if($id){
	        return $id;
	    }else{
	        return 0;
	    }
	}
	function test(){
		$res=$this->encrypt("123");
		$res1=$this->decrypt($res);
		//$result=openssl_decrypt(base64_decode('txQuKgE7gTx/yk3pZ2IJ3w=='), "aes-256-cbc", $this->Key, true, str_repeat(chr(0), 16));
		var_dump($res);
		var_dump($res1);
	}
	function test1(){
		$res=$this->encrypt1("123","384f8f5b973f8518a1f70fd40d26b310");
		$res1=$this->decrypt1($res,"384f8f5b973f8518a1f70fd40d26b310");
		//$result=openssl_decrypt(base64_decode('txQuKgE7gTx/yk3pZ2IJ3w=='), "aes-256-cbc", $this->Key, true, str_repeat(chr(0), 16));
		var_dump($res);
		var_dump($res1);
	}
	///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	 function encrypt1($str, $encryptKey)
    {
        $localKeyBase64 = base64_decode($encryptKey);
        $str = trim($str);
        $str = $this->addPKCS7Padding1($str);
        $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB), MCRYPT_RAND);
        $encrypt_str = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $localKeyBase64, $str, MCRYPT_MODE_ECB, $iv);
        return base64_encode($encrypt_str);
    }
 
    /**
     *  ES-128 ECB模式加密数据
     * @param $str 待解密字符串
     * @param $encryptKey 秘钥
     * @return bool|string 返回解密后的字符串
     */
   function decrypt1($str, $encryptKey)
    {
 
        $str = base64_decode($str);
        $localKeyBase64 = base64_decode($encryptKey);
        $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB), MCRYPT_RAND);
        $encrypt_str = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $localKeyBase64, $str, MCRYPT_MODE_ECB, $iv);
        $encrypt_str = trim($encrypt_str);
        $encrypt_str = $this->stripPKSC7Padding1($encrypt_str);
        return $encrypt_str;
 
    }
 
 
    function addPKCS7Padding1($source)
    {
        $source = trim($source);
        $block = mcrypt_get_block_size('rijndael-128', 'ecb');
        $pad = $block - (strlen($source) % $block);
        if ($pad <= $block) {
            $char = chr($pad);
            $source .= str_repeat($char, $pad);
        }
        return $source;
    }
 
    function stripPKSC7Padding1($source)
    {
        $source = trim($source);
        $char = substr($source, -1);
        $num = ord($char);
        if ($num == 62) return $source;
        $source = substr($source, 0, -$num);
        return $source;
    }
	
}
